<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card class="box-card" shadow="never">
        <!-- 标题 -->
        <div slot="header" class="title">
          {{ detailId ? "试题修改" : "试题录入" }}
        </div>
        <!-- 表单 -->
        <el-form
          ref="testFormRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          label-position="left"
        >
          <!-- 学科 -->
          <el-form-item label="学科:" prop="subjectID">
            <el-select
              v-model="formData.subjectID"
              placeholder="请选择"
              @input="subjectChange(formData.subjectID)"
              :style="{ width: '400px' }"
            >
              <el-option
                v-for="(item, index) in subjectOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 目录 -->
          <el-form-item label="目录:" prop="catalogID">
            <el-select
              v-model="formData.catalogID"
              placeholder="请选择"
              :style="{ width: '400px' }"
            >
              <el-option
                v-for="(item, index) in catalogOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 企业 -->
          <el-form-item label="企业:" prop="enterpriseID">
            <el-select
              v-model="formData.enterpriseID"
              placeholder="请选择"
              :style="{ width: '400px' }"
            >
              <el-option
                v-for="(item, index) in enterpriseOptions"
                :key="index"
                :label="item.company"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 城市 -->
          <el-form-item label="城市:" prop="province" class="citySelect">
            <!-- 选择市 -->
            <el-select
              class="filter-item"
              v-model="formData.province"
              style="margin-right: 2.5px"
              @keyup.enter="handleFilter"
              @change="handleProvince"
              filterable
            >
              <el-option
                v-for="item in citySelect.province"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
            <!-- 选择区 -->
            <el-select
              class="filter-item"
              style="margin-left: 2.5px"
              v-model="formData.city"
              @keyup.enter="handleFilter"
              filterable
            >
              <el-option
                v-for="item in citySelect.cityDate"
                :key="item"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 方向 -->
          <el-form-item label="方向:" prop="direction">
            <el-select
              v-model="formData.direction"
              placeholder="请选择"
              :style="{ width: '400px' }"
            >
              <el-option
                v-for="(item, index) in direction"
                :key="index"
                :value="item"
                :label="item"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 题型 -->
          <el-form-item label="题型:" prop="questionType">
            <el-radio-group v-model="formData.questionType" @input="TypeChange">
              <el-radio
                v-for="(item, index) in questionType"
                :key="index"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 难度 -->
          <el-form-item label="难度:" prop="difficulty">
            <el-radio-group v-model="formData.difficulty">
              <el-radio
                v-for="(item, index) in difficulty"
                :key="index"
                :label="item.value"
                >{{ item.label }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!-- 题干 -->
          <el-form-item label="题干:" prop="question">
            <quill-editor
              ref="questionQuillEditor"
              v-model="formData.question"
              :options="editorOption"
              class="editor"
              @blur="questionBlur('question')"
            ></quill-editor>
          </el-form-item>
          <!-- 选项 -->
          <el-form-item
            label="选项:"
            class="options-box"
            v-show="formData.questionType !== 3"
          >
            <!-- 单选 -->
            <el-radio-group
              v-model="radioOption"
              v-if="formData.questionType == 1"
              @input="radioChange"
            >
              <el-radio
                v-for="(item, index) in formData.options"
                :key="index"
                :label="item.code"
                >{{ item.code }}:
                <!-- 内容 -->
                <el-input v-model="item.title" style="width: 240px"></el-input>
                <!-- 上传图片 -->
                <el-upload
                  class="uploadImg"
                  :show-file-list="false"
                  list-type="picture-card"
                  action="https://jsonplaceholder.typicode.com/posts/"
                >
                  <span>上传图片</span>
                  <i class="el-icon-circle-close"></i>
                </el-upload>
              </el-radio>
            </el-radio-group>
            <!-- 多选 -->
            <el-checkbox-group
              v-model="checkList"
              v-if="formData.questionType == 2"
              @input="checkboxChange"
            >
              <el-checkbox
                v-for="(item, index) in formData.options"
                :key="index"
                :label="item.code"
                >{{ item.code }}:
                <!-- 内容 -->
                <el-input v-model="item.title" style="width: 240px"></el-input>
                <!-- 上传图片 -->
                <el-upload
                  class="uploadImg"
                  :show-file-list="false"
                  list-type="picture-card"
                  action="https://jsonplaceholder.typicode.com/posts/"
                >
                  <span>上传图片</span>
                  <i class="el-icon-circle-close"></i>
                </el-upload>
              </el-checkbox>
            </el-checkbox-group>
            <el-col>
              <el-button
                type="danger"
                size="small"
                @click="addOptions"
                :disabled="formData.questionType == 1"
                >+增加选项与答案</el-button
              >
            </el-col>
          </el-form-item>
          <!-- 解析视频 -->
          <el-form-item label="解析视频">
            <el-input
              v-model="formData.videoURL"
              style="width: 400px"
            ></el-input>
          </el-form-item>
          <!-- 答案解析 -->
          <el-form-item label="答案解析" prop="answer">
            <quill-editor
              ref="answerQuillEditor"
              v-model="formData.answer"
              :options="editorOption"
              class="editor"
              @blur="questionBlur('answer')"
            ></quill-editor>
          </el-form-item>
          <!-- 题目备注 -->
          <el-form-item label="题目备注">
            <el-input
              type="textarea"
              :rows="5"
              placeholder="请输入内容"
              v-model="formData.remarks"
              style="width: 400px"
            >
            </el-input>
          </el-form-item>
          <!-- 试题标签 -->
          <el-form-item label="试题标签">
            <el-select
              v-model="formData.tags"
              multiple
              filterable
              placeholder="请选择"
              :style="{ width: '400px' }"
            >
              <el-option
                v-for="(item, index) in tagsOptions"
                :key="index"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <!-- 提交或修改 -->
          <el-form-item>
            <el-button
              :type="detailId ? 'success' : 'primary'"
              @click="onSubmit"
              >{{ detailId ? "确认修改" : "确认提交" }}</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
import { direction, difficulty, questionType } from '@/api/hmmm/constants.js'
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as subjectList } from '@/api/hmmm/subjects.js'
import { simple as catalogList } from '@/api/hmmm/directorys.js'
import { list as enterpriseList } from '@/api/hmmm/companys.js'
import { simple as tagsList } from '@/api/hmmm/tags.js'
import { add as testQuestions, detail as testDetails, update as updateDetails } from '@/api/hmmm/questions.js'

// 引入样式和quillEditor
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { quillEditor } from 'vue-quill-editor'

// 引入lodash
import _ from 'lodash'

// 工具栏配置项
const toolbarOptions = [
  // 加粗 斜体 下划线 删除线 -----['bold', 'italic', 'underline', 'strike']
  ['bold', 'italic', 'underline', 'strike'],
  // 有序、无序列表-----[{ list: 'ordered' }, { list: 'bullet' }]
  [{ list: 'ordered' }, { list: 'bullet' }],
  // 引用  代码块-----['blockquote', 'code-block']
  ['blockquote'],
  // 链接、图片、视频-----['link', 'image', 'video']
  ['code-block', 'image', 'link']
]
export default {
  name: 'QuestionsNew',
  // 注册 quillEditor
  components: {
    quillEditor
  },
  data () {
    return {
      // 单项数组
      radioOption: '',
      // 多选数组
      checkList: [],
      // 城市列表
      citySelect: {
        province: [],
        cityDate: []
      },
      // 题目id
      detailId: this.$route.query.username,
      // 表单数据
      formData: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: 1, // 题型
        difficulty: 1, // 难度
        question: '', // 题干
        options: [
          {
            code: 'A',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'B',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'C',
            title: '',
            img: '',
            isRight: 0
          },
          {
            code: 'D',
            title: '',
            img: '',
            isRight: 0
          }
        ], // 选项
        videoURL: '', // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '' // 试题标签
      },
      // 表单验证规则
      rules: {
        subjectID: [{
          required: true,
          message: '请选择学科',
          trigger: 'change'
        }],
        catalogID: [{
          required: true,
          message: '请选择目录',
          trigger: 'change'
        }],
        enterpriseID: [{
          required: true,
          message: '请选择企业',
          trigger: 'change'
        }],
        province: [{
          required: true,
          message: '请选择城市',
          trigger: 'change'
        }],
        direction: [{
          required: true,
          message: '请选择方向',
          trigger: 'change'
        }],
        questionType: [{
          required: true,
          message: '请选择题型',
          trigger: 'change'
        }],
        difficulty: [{
          required: true,
          message: '请选择难度',
          trigger: 'change'
        }],
        question: [{
          required: true,
          message: '请输入题干',
          trigger: 'blur'
        }],
        answer: [{
          required: true,
          message: '请输入答案解析',
          trigger: 'blur'
        }]
      },
      subjectOptions: [], // 学科列表
      catalogOptions: [], // 学科目录列表
      enterpriseOptions: [], // 企业列表
      direction, // 方向数据
      questionType, // 题型
      difficulty, // 难度
      tagsOptions: [], // 试题标签
      content: '', // 富文本内容
      // 富文本配置项
      editorOption: {
        modules: {
          toolbar: toolbarOptions
        },
        theme: 'snow',
        placeholder: ''
      }
    }
  },

  created () {
    // 获取数据，进行修改
    if (this.detailId) {
      this.getTestDetails(this.detailId)
    }
    // 获取城市列表
    this.getCityData()
    // 获取学科列表
    this.getSubjectList()
    // 获取企业列表
    this.getEnterpriseList()
  },
  methods: {
    // 获取数据,进行试题修改
    async getTestDetails (id) {
      try {
        const { data: res } = await testDetails({ id })
        this.subjectChange(res.subjectID)
        this.formData = res
        this.formData.tags = this.getToArray(this.formData.tags)
        this.formData.options.forEach(item => {
          if (item.isRight === 1) {
            this.radioOption = item.code
            this.checkList.push(item.code)
          }
        })
        this.formData.questionType = Number(this.formData.questionType)
        this.formData.difficulty = Number(this.formData.difficulty)
      } catch (err) {
        console.log(err)
      }
    },
    // 字符串转数组方法
    getToArray (str) {
      if (!str.includes(',')) {
        return new Array(str)
      } else {
        return str.split(',')
      }
    },
    // 获取学科列表
    async getSubjectList () {
      try {
        const { data: res } = await subjectList()
        this.subjectOptions = res
      } catch (err) {
        console.log(err)
      }
    },
    // 获取学科目录
    async getCatalogList (subjectID) {
      this.formData.catalogID = ''
      try {
        const { data: res } = await catalogList({ subjectID })
        this.catalogOptions = res
      } catch (err) {
        console.log(err)
      }
    },
    // 获取企业列表
    async getEnterpriseList () {
      try {
        const { data: res } = await enterpriseList()
        this.enterpriseOptions = res.items
      } catch (err) {
        console.log(err)
      }
    },
    // 获取城市
    getCityData: function () {
      this.citySelect.province = provinces()
    },
    // 获取地区
    handleProvince: function (e) {
      this.citySelect.cityDate = citys(e)
      this.formData.city = this.citySelect.cityDate[0]
    },
    // 获取试题标签列表
    async getTagsList (subjectID) {
      try {
        const { data: res } = await tagsList({ subjectID })
        this.tagsOptions = res
      } catch (err) {
        console.log(err)
      }
    },
    // 学科内容发生改变
    subjectChange (id) {
      this.formData.tags = ''
      this.getCatalogList(id)
      this.getTagsList(id)
    },
    // 表单提交
    onSubmit () {
      this.$refs.testFormRef.validate(async valid => {
        if (!valid) return false
        try {
          this.formData.tags = this.formData.tags ? this.formData.tags.join(',') : this.formData.tags = '  '
          this.formData.questionType = this.formData.questionType.toString()
          this.formData.difficulty = this.formData.difficulty.toString()
          if (this.formData.questionType === '3') {
            this.formData.options = [{
              code: 'A',
              title: '',
              img: '',
              isRight: 0
            },
            {
              code: 'B',
              title: '',
              img: '',
              isRight: 0
            },
            {
              code: 'C',
              title: '',
              img: '',
              isRight: 0
            },
            {
              code: 'D',
              title: '',
              img: '',
              isRight: 0
            }]
          }
          if (this.detailId) {
            this.formData.remarks = ' '
            this.formData.videoURL = ' '
            await updateDetails(this.formData)
          } else {
            this.formData = _.omitBy(this.formData, (value, key) => _.isEmpty(value) && !_.isNumber(value))
            await testQuestions(this.formData)
          }
          this.$router.push('/questions/list')
          this.$message({
            message: '提交成功',
            type: 'success'
          })
        } catch (err) {
          console.log(err)
          this.$message({
            message: '提交失败,请稍后重试',
            type: 'error'
          })
        }
      })
    },
    // 添加选项
    addOptions () {
      this.formData.options.push({
        code: String.fromCharCode(65 + this.formData.options.length),
        title: '',
        img: '',
        isRight: 0
      })
    },
    // 富文本校验
    questionBlur (val) {
      this.$refs.testFormRef.validateField(val)
    },
    // 单选改变
    radioChange (val) {
      // 清空其他的isRight
      this.formData.options.forEach(item => {
        item.isRight = 0
      })
      this.formData.options.forEach(item => {
        if (item.code === val) item.isRight = 1
      })
    },
    // 多选改变
    checkboxChange (val) {
      // 清空其他的isRight
      this.formData.options.forEach(item => {
        item.isRight = 0
      })
      val.forEach(item => this.formData.options.forEach(val => {
        if (val.code === item) val.isRight = 1
      }))
    },
    // 题型改变
    TypeChange (val) {
      if (val === 1) this.radioChange(this.radioOption)
      if (val === 2) this.checkboxChange(this.checkList)
    }
  }
}
</script>

<style scoped lang='less'>
.app-container {
  .options-box {
    .el-radio,
    .el-checkbox {
      display: block;
      margin: 20px 0;
    }
    /deep/ .el-radio,
    .el-checkbox {
      width: 400px;
      padding: 0 15px;
    }
    /deep/ .el-radio{
      line-height: 19px;
    }
  }
  .citySelect {
    /deep/ .el-form-item__content {
      display: flex;
      width: 400px;
      box-sizing: border-box;
    }
  }
  .uploadImg {
    display: inline-block;
    i {
      position: absolute;
      top: -10px;
      right: -8px;
      z-index: 99;
      font-size: 18px;
      color: #999;
      background-color: #fff;
    }
  }
  /deep/ .el-upload--picture-card {
    background-color: #fff;
    border-radius: 6px;
    width: 100px;
    height: 60px;
    line-height: 60px;
    text-align: center;
    display: inline-block;
    position: relative;
    top: -23px;
    margin-left: 4px;
    .el-icon-plus {
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .editor {
    height: 200px;
    margin-bottom: 55px;
    line-height: 32px;
    width: 100%;
    /deep/ .ql-toolbar.ql-snow {
      padding: 0 0 0 8px;
    }
  }
}
</style>
